import Config from './config.js'
import { getToken, setToken, removeToken ,refreshToken} from '@/common/auth'
import { inArray } from '@/common/common';

async function request_async(option) 
{
	if (option.name) {
		option.url  = Config.url[option.name]
	}
	if(option.suffix){
		option.url = option.url + option.suffix
	}
	option.header = {
		'Content-Type':'application/x-www-form-urlencoded'
	}
	//同步更新token,并更新token
	var token = getToken();
	if(option.data && option.data.token){
		token = option.data.token;
	}
	
	if(option.name != 'user.login' && option.name != 'user.register'){
		var tmpToken = await refreshToken();
		
		if(tmpToken){
			token = tmpToken;
		}
	}
	// console.log('token: ', token);
	if(token){
		option.header['Authorization'] = 'Bearer ' + token;
	}
	// console.log(option)
	return new Promise((resolve, reject) => {
		
		option.success = function(res){
			
			/*
			data: {code: 1, msg: "电话 大小必须为 11。", data: Array(1)}
			errMsg: "request:ok"
			header: {cache-control: "no-cache, private", content-type: "application/json"}
			statusCode: 200
			*/
			if(res.statusCode && res.statusCode >= 400){
				console.log('error statusCode', res.statusCode, res);
				if(Config.show_err){
					uni.showModal({
						title: '异常', 
						content: ''+res.data.message,
						showCancel: false
					});
				}
				if((res.data.message.indexOf('Token') !== false && token) || ! token){
					//刷新token
					var pages = getCurrentPages();
					var route = (pages[pages.length - 1]).route;
					console.log('route: ', route);
					if(inArray(route, Config.no_authed_pages)){
						return false;
					}
					uni.showModal({
					    content: Config.common_text.login_expired,
						showCancel: false,
						success: function(res){
							uni.navigateTo({
								url: `/pages/public/login?relogin=1`
							})
						}
					});
				} 
			}
			resolve(res.data);
		}
		option.fail = function(err){
			console.log('err: ', err);
			reject(err);
		}
		
	    uni.request(option);
	})
}

export default request_async